//
//  AsyncPOSTParser.m
//  SmileRead
//
//  Created by dllo on 15/8/24.
//  Copyright (c) 2015年 JIZ. All rights reserved.
//

#import "AsyncPOSTParser.h"
#import "Reachability.h"
#import "Path.h"
#import "MBProgressHUD.h"
#import "AppDelegate.h"

@interface AsyncPOSTParser ()<NSURLConnectionDataDelegate, NSURLConnectionDelegate>

@property (nonatomic, retain) NSMutableData *reData;
@property (nonatomic, retain) NSString *fileName;

@property (nonatomic, retain) MBProgressHUD *mb;


@end

@implementation AsyncPOSTParser

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.reData = [NSMutableData data];
    }
    return self;
}

- (void)dealloc
{
    Block_release(_myBlock);
    [_reData release];
    [super dealloc];
}

+ (instancetype)asyncPOSTParserWithURLString:(NSString *)Urlstr fileName:(NSString *)fileName pamarters:(NSDictionary *)pamaters block:(void(^)(NSData *data))block
{
    
    AsyncPOSTParser *parser = [[AsyncPOSTParser alloc] init];
    parser.fileName = fileName;
    parser.myBlock = block;
    
    NSMutableString *string = [NSMutableString string];
    for (NSString *key in pamaters) {
        
        if ([string length] == 0) {
            [string appendFormat:@"%@=%@", key, [pamaters objectForKey:key]];
        }
        else {
            string = [NSString stringWithFormat:@"%@&%@=%@", string, key, [pamaters objectForKey:key]].mutableCopy;
        }
    }
    
    Urlstr = [Urlstr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    string = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding].mutableCopy;
    
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    if ([reach isReachable]) {
        [parser startParserWithURLString:Urlstr body:string];
    }
    else {
        
        NSLog(@"无网的状态");
        
        // 判断文件是否存在
        NSString *path = [Path pathOfLibraryWithFileName:parser.fileName];
        NSFileManager *file = [NSFileManager defaultManager];
        // 有缓存
        if ([file fileExistsAtPath:path]) {
            // 从文件中读取数据
            NSData *data = [NSData dataWithContentsOfFile:path];
            
            parser.myBlock(data);
        }
        // 无网无数据
        else {
            NSLog(@"无网无数据");
        }

    }
    return [parser autorelease];
}

- (void)startParserWithURLString:(NSString *)UrlStr body:(NSString *)body
{
    AppDelegate *tempAppDelegate = [[UIApplication sharedApplication] delegate];
    self.mb = [MBProgressHUD showHUDAddedTo:tempAppDelegate.window animated:YES];
    self.mb.labelText = @"正在加载";
    [self.mb hide:YES afterDelay:10];
    [self.mb show:YES];
    
    NSURL *url = [NSURL URLWithString:UrlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    NSData *data = [body dataUsingEncoding:NSUTF8StringEncoding];
    request.HTTPBody = data;
    
    [NSURLConnection connectionWithRequest:request delegate:self];
    
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"网络解析错误: %@", error);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.mb removeFromSuperview];
    [self.reData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    
    // 数据加载完成后, 将数据存入本地
    NSString *path = [Path pathOfLibraryWithFileName:self.fileName];
    NSFileManager *file = [NSFileManager defaultManager];
    if ([file fileExistsAtPath:path]) {
        [file removeItemAtPath:path error:nil];
        [self.reData writeToFile:path atomically:YES];
    }
    [self.reData writeToFile:path atomically:YES];
    self.myBlock(self.reData);
}

@end
